package com.thememaker.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.util.FileUtils;
import com.thememaker.lockstyle.LockstylePaserUtils;
import com.thememaker.lockstyle.LockstyleShowUtils;
import com.thememaker.lockstyle.bean.Lockscreen;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class AutoSaveUtils {

    private static AutoSaveUtils autoSaveUtils;
    private ThemeFileInfo themeFileInfo;
    private Path lockscreenRecordPath;
    private ScheduledExecutorService scheduledExecutorService;
    private int autoSaveInterval = 40;

    public void setThemeFileInfo(ThemeFileInfo themeFileInfo) {
        this.themeFileInfo = themeFileInfo;
    }

    public static AutoSaveUtils getInstance(ThemeFileInfo themeFileInfo){
        if (autoSaveUtils == null){
            autoSaveUtils = new AutoSaveUtils();
        }
        autoSaveUtils.setThemeFileInfo(themeFileInfo);
        if (autoSaveUtils.lockscreenRecordPath == null){
            autoSaveUtils.init();
        }
        return autoSaveUtils;
    }

    private AutoSaveUtils(){}

    private void init(){

        lockscreenRecordPath = Paths.get(themeFileInfo.getThemeDir().getPath(), themeFileInfo.getThemeType(), ThemeFileInfo.LOCKSTYLE_NAME, "lockscreenRecord.json");
    }

    public void startAutoSave(LockstyleShowUtils lockstyleShowUtils){
        System.err.println("自动保存 启动");
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(()->{
            System.err.println("自动保存 >>>> " +LocalTime.now());
            if (lockstyleShowUtils != null){

                LocalDateTime localDateTime = Optional.ofNullable(getSaveRecord())
                        .flatMap(recorcd -> Optional.ofNullable(recorcd.getSaveTime()))
                        .orElse(LocalDateTime.now().minusDays(1));
                Duration duration = Duration.between(localDateTime,LocalDateTime.now());
                System.err.println("时间对比 >>> " + duration.getSeconds());
                if (duration.getSeconds() > autoSaveInterval/2){
                    LockstylePaserUtils.saveLockScreenXml(themeFileInfo,lockstyleShowUtils.getDocument(),lockstyleShowUtils.getLockscreen(),Paths.get(lockstyleShowUtils.getLockscreenPath().toString(), "manifest.xml").toFile());
                }
            }
        },autoSaveInterval,autoSaveInterval,TimeUnit.SECONDS);
    }

    public void stopSave(){
        System.err.println("自动保存 关闭");
        if (scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService.shutdownNow();
            scheduledExecutorService = null;
        }
    }

    private LockscreenRecord getSaveRecord(){
        LockscreenRecord lockscreenRecord = null;
        if (Files.exists(lockscreenRecordPath)) {
            String str = null;
            try {
                str = new String(Files.readAllBytes(lockscreenRecordPath), "UTF-8");
                lockscreenRecord = new Gson().fromJson(str,
                        new TypeToken<LockscreenRecord>() {
                        }.getType());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lockscreenRecord;
    }


    public void saveRecord(Lockscreen lockscreen){
        System.err.println("保存记录");
        if (!Files.exists(lockscreenRecordPath)){
            try {
                Files.createDirectories(lockscreenRecordPath.getParent());
                Files.createFile(lockscreenRecordPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LockscreenRecord lockscreenRecord = new LockscreenRecord(LocalDateTime.now(),lockscreen);
        try (BufferedWriter writer = Files.newBufferedWriter(lockscreenRecordPath)) {
            writer.write(new Gson().toJson(lockscreenRecord));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    class LockscreenRecord{
        private LocalDateTime saveTime;
        private Lockscreen lockscreen;

        public LocalDateTime getSaveTime() {
            return saveTime;
        }

        public void setSaveTime(LocalDateTime saveTime) {
            this.saveTime = saveTime;
        }

        public Lockscreen getLockscreen() {
            return lockscreen;
        }

        public void setLockscreen(Lockscreen lockscreen) {
            this.lockscreen = lockscreen;
        }

        public LockscreenRecord(LocalDateTime saveTime, Lockscreen lockscreen) {
            this.saveTime = saveTime;
            this.lockscreen = lockscreen;
        }
    }

}
